package timberman.core;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.resolvers.ResolutionFileResolver.Resolution;
import com.badlogic.gdx.files.FileHandle;

public class ResolutionFileResolver implements FileHandleResolver {

	protected final FileHandleResolver baseResolver;
	protected final Resolution resolution;

	public ResolutionFileResolver(FileHandleResolver baseResolver,
			Resolution resolution) {
		this.baseResolver = baseResolver;
		this.resolution = resolution;
	}

	@Override
	public FileHandle resolve(String fileName) {
		FileHandle originalHandle = new FileHandle(fileName);
		FileHandle handle = baseResolver.resolve(resolve(originalHandle,
				resolution.suffix));
		if (!handle.exists()) {
			handle = baseResolver.resolve(resolveDefault(originalHandle));
		}
		if (fileName.startsWith("data/graphics")) {
			String newFile = fileName.replace("data/graphics", "data/graphics/"
					+ resolution.suffix);
			handle = baseResolver.resolve(newFile);
		}
		if (!handle.exists())
			handle = baseResolver.resolve(fileName);
		return handle;
	}

	protected String resolveDefault(FileHandle originalHandle) {
		return originalHandle.parent() + "/640960/" + originalHandle.name();
	}

	protected String resolve(FileHandle originalHandle, String suffix) {
		return originalHandle.parent() + "/" + suffix + "/"
				+ originalHandle.name();
	}

	static public Resolution choose(Resolution... descriptors) {
		if (descriptors == null)
			throw new IllegalArgumentException("descriptors cannot be null.");
		int w = Gdx.graphics.getWidth(), h = Gdx.graphics.getHeight();
		int min = Integer.MAX_VALUE;
		int tmp = 0;
		// Prefer the shortest side.
		Resolution best = descriptors[0];
		if (w < h) {
			for (int i = 0, n = descriptors.length; i < n; i++) {
				Resolution other = descriptors[i];
				tmp = (w - other.portraitWidth) * (w - other.portraitWidth)
						+ (h - other.portraitHeight)
						* (h - other.portraitHeight);
				if (tmp < min) {
					best = other;
					min = tmp;
				}
			}
		} else {
			for (int i = 0, n = descriptors.length; i < n; i++) {
				Resolution other = descriptors[i];
				tmp = (h - other.portraitWidth) * (h - other.portraitWidth)
						+ (w - other.portraitHeight)
						* (w - other.portraitHeight);
				if (tmp < min) {
					best = other;
					min = tmp;
				}
			}
		}
		return best;
	}
}
